/**
 * API数据获取和操作钩子集合
 * 
 * 本模块提供了一套封装良好的数据获取和操作钩子，基于React Query实现。
 * 主要职责：
 * 1. 从各种API端点获取数据（用户、角色、权限、新闻等）
 * 2. 处理API响应的不同格式，确保返回一致的数据结构
 * 3. 提供数据修改操作（添加、更新、删除）并管理缓存失效
 * 4. 统一处理成功和错误消息提示
 * 
 * 这些钩子从各个业务组件中抽离出数据获取逻辑，实现了关注点分离，
 * 使组件专注于UI渲染而不用处理复杂的数据获取和状态管理逻辑。
 * 
 * @module hooks/useAPI
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { message } from 'antd';

// 按需导入API，而不是导入整个模块
import { 
  getUserList, 
  getUserById, 
  addUser,
  updateUser, 
  deleteUser,
  getUserProfile,
  uploadAvatar,
  changePassword
} from '../api/userApi';
import { getRoleList } from '../api/roleApi';
import { getRights } from '../api/rightsApi';
import { 
  getNewsList, 
  getNewsById, 
  addNews, 
  updateNews, 
  deleteNews 
} from '../api/newsApi';
import { getCategories } from '../api/categoryApi';

// 从types中导入类型定义
import { User, Role, Right, News, Category } from '../types';

// 定义API响应类型 - 扩展以匹配项目中可能的各种响应格式
interface ApiResponse<T = unknown> {
  data?: T | { data?: T };
  code?: number;
  status?: number;
  msg?: string;
  message?: string;
  success?: boolean;
}

// 定义通用的嵌套数据结构类型
interface NestedData<T> {
  data?: T;
  [key: string]: unknown;
}

// 辅助函数：处理API响应数据，统一格式 - 改进类型安全性
function processApiResponse<T>(response: ApiResponse<T | T[]> | T[]): T[] {
  if (Array.isArray(response)) {
    return response as T[];
  } else if (response && typeof response === 'object') {
    const data = response.data;
    
    if (Array.isArray(data)) {
      return data as T[];
    } else if (data && typeof data === 'object') {
      // 处理嵌套数据结构，避免使用any
      const nestedData = data as NestedData<T[]>;
      if (nestedData.data && Array.isArray(nestedData.data)) {
        return nestedData.data;
      }
    }
  }
  return [] as T[];
}

// 辅助函数：从错误对象中提取错误消息
function extractErrorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  } else if (typeof error === 'object' && error !== null) {
    const errorObj = error as Record<string, unknown>;
    if (errorObj.message && typeof errorObj.message === 'string') {
      return errorObj.message;
    }
    if (errorObj.msg && typeof errorObj.msg === 'string') {
      return errorObj.msg;
    }
    if (errorObj.error && typeof errorObj.error === 'string') {
      return errorObj.error;
    }
  }
  return '操作失败';
}

// ===== 用户个人资料相关钩子 =====

/**
 * 获取当前用户个人资料的Hook
 */
export const useUserProfile = () => {
  return useQuery({
    queryKey: ['userProfile'],
    queryFn: async () => {
      try {
        return await getUserProfile();
      } catch (error) {
        console.error('获取个人资料失败:', error);
        throw error;
      }
    }
  });
};

/**
 * 更新用户头像的Hook
 */
export const useUpdateAvatar = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (file: File) => uploadAvatar(file),
    onSuccess: (data) => {
      message.success('头像更新成功');
      // 更新相关查询缓存
      queryClient.invalidateQueries({ queryKey: ['userProfile'] });
      return data;
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`头像更新失败: ${errorMsg}`);
    }
  });
};

/**
 * 修改密码的Hook
 */
export const useChangePassword = () => {
  return useMutation({
    mutationFn: ({ oldPassword, newPassword }: { oldPassword: string; newPassword: string }) => 
      changePassword(oldPassword, newPassword),
    onSuccess: () => {
      message.success('密码修改成功');
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`密码修改失败: ${errorMsg}`);
    }
  });
};

// ===== 用户管理相关钩子 =====

/**
 * 获取用户列表的Hook
 */
export const useUsers = () => {
  return useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      try {
        const res = await getUserList();
        return processApiResponse<User>(res as ApiResponse<User[]> | User[]);
      } catch (error) {
        console.error('获取用户列表失败:', error);
        return [] as User[];
      }
    }
  });
};

/**
 * 获取单个用户详情的Hook
 */
export const useUserById = (id?: string | number) => {
  return useQuery({
    queryKey: ['user', id],
    queryFn: async () => {
      if (!id) return null;
      try {
        return await getUserById(id);
      } catch (error) {
        console.error(`获取用户详情失败(ID=${id}):`, error);
        return null;
      }
    },
    enabled: !!id // 只有当id存在时才执行查询
  });
};

/**
 * 添加用户的Hook
 */
export const useAddUser = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (userData: Omit<User, 'id'>) => addUser(userData),
    onSuccess: () => {
      message.success('用户添加成功');
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`用户添加失败: ${errorMsg}`);
    }
  });
};

/**
 * 更新用户的Hook
 */
export const useUpdateUser = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, data }: { id: number | string, data: Partial<User> }) => 
      updateUser(id, data),
    onSuccess: (_, variables) => {
      message.success('用户更新成功');
      queryClient.invalidateQueries({ queryKey: ['users'] });
      queryClient.invalidateQueries({ queryKey: ['user', variables.id] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`用户更新失败: ${errorMsg}`);
    }
  });
};

/**
 * 删除用户的Hook
 */
export const useDeleteUser = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number | string) => deleteUser(id),
    onSuccess: () => {
      message.success('用户删除成功');
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`用户删除失败: ${errorMsg}`);
    }
  });
};

// ===== 角色相关钩子 =====

/**
 * 获取角色列表的Hook
 */
export const useRoles = () => {
  return useQuery({
    queryKey: ['roles'],
    queryFn: async () => {
      try {
        const res = await getRoleList();
        return processApiResponse<Role>(res as ApiResponse<Role[]> | Role[]);
      } catch (error) {
        console.error('获取角色列表失败:', error);
        return [] as Role[];
      }
    }
  });
};

// ===== 权限相关钩子 =====

/**
 * 获取权限列表的Hook
 */
export const useRights = () => {
  return useQuery({
    queryKey: ['rights'],
    queryFn: async () => {
      try {
        const res = await getRights();
        return processApiResponse<Right>(res as ApiResponse<Right[]> | Right[]);
      } catch (error) {
        console.error('获取权限列表失败:', error);
        return [] as Right[];
      }
    }
  });
};

// ===== 新闻相关钩子 =====

/**
 * 获取新闻列表的Hook
 */
export const useNews = (params?: Record<string, string | number | boolean>) => {
  return useQuery({
    queryKey: ['news', params],
    queryFn: async () => {
      try {
        const res = await getNewsList(params);
        return processApiResponse<News>(res as ApiResponse<News[]> | News[]);
      } catch (error) {
        console.error('获取新闻列表失败:', error);
        return [] as News[];
      }
    }
  });
};

/**
 * 获取单条新闻详情的Hook
 */
export const useNewsById = (id?: number | string) => {
  return useQuery({
    queryKey: ['news', id],
    queryFn: async () => {
      if (!id) return null;
      try {
        const res = await getNewsById(id);
        // 处理单个对象响应
        if (res && typeof res === 'object') {
          if ('data' in res) {
            const data = res.data;
            if (data && typeof data === 'object') {
              if ('data' in data && data.data) {
                return data.data as News;
              }
              return data as News;
            }
          }
          return res as News;
        }
        return null;
      } catch (error) {
        console.error(`获取新闻详情失败(ID=${id}):`, error);
        return null;
      }
    },
    enabled: !!id // 只有当id存在时才执行查询
  });
};

/**
 * 添加新闻的Hook
 */
export const useAddNews = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (newsData: Omit<News, 'id'>) => addNews(newsData),
    onSuccess: () => {
      message.success('新闻添加成功');
      queryClient.invalidateQueries({ queryKey: ['news'] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`新闻添加失败: ${errorMsg}`);
    }
  });
};

/**
 * 更新新闻的Hook
 */
export const useUpdateNews = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: ({ id, data }: { id: number | string, data: Partial<News> }) => 
      updateNews(id, data),
    onSuccess: (_, variables) => {
      message.success('新闻更新成功');
      queryClient.invalidateQueries({ queryKey: ['news'] });
      queryClient.invalidateQueries({ queryKey: ['news', variables.id] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`新闻更新失败: ${errorMsg}`);
    }
  });
};

/**
 * 删除新闻的Hook
 */
export const useDeleteNews = () => {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: (id: number | string) => deleteNews(id),
    onSuccess: () => {
      message.success('新闻删除成功');
      queryClient.invalidateQueries({ queryKey: ['news'] });
    },
    onError: (error) => {
      const errorMsg = extractErrorMessage(error);
      message.error(`新闻删除失败: ${errorMsg}`);
    }
  });
};

// ===== 分类相关钩子 =====

/**
 * 获取分类列表的Hook
 */
export const useCategories = () => {
  return useQuery({
    queryKey: ['categories'],
    queryFn: async () => {
      try {
        const res = await getCategories();
        return processApiResponse<Category>(res as ApiResponse<Category[]> | Category[]);
      } catch (error) {
        console.error('获取分类列表失败:', error);
        return [] as Category[];
      }
    }
  });
}; 